/**
 * 站点编辑、新增
 *
 * @author liuxiaotang
 */
define(["app", "js/services/MessageBox", "js/services/MuseService", "js/directives/FileUpload"
    , 'async!BMap'], function (app) {

    var deps = ["$scope", "$state", "$modal", "$stateParams", "MessageBox", "MuseService"];

    function controller ($scope, $state, $modal, $stateParams, MessageBox, MuseService) {
        //获取参数
        var id = $stateParams.id || '';

        //获取数据
        $scope.getDetail = function () {
            MuseService.get(baseServices_restfulUrl + "routeSite/load.json?id=" + id).success(
                function (data, status, headers, config) {
                    if (data.state == 0) {
                        $scope.routeSite = data.data;
                        addMarker($scope.routeSite.longitude, $scope.routeSite.latitude, 18);
                    } else {
                        MessageBox.notify('获取数据失败:' + data.message);
                    }
                });
        };
        if (id) {
            $scope.getDetail();
        }

        //保存
        $scope.saveObj = function () {
            MuseService.postObj(baseServices_restfulUrl + "routeSite/save.json", $scope.routeSite).success(
                function (data, status, headers, config) {
                    if (data.state == 0) {
                        $scope.result = data.data;
                        MessageBox.notify('保存成功!');
                        $state.go('routeSiteList');
                    } else {
                        MessageBox.notify('保存失败：' + data.message);
                    }
                });
        };

        // 取消，返回
        $scope.close = function () {
            $state.go("routeSiteList");
        };

        var map = new BMap.Map("allmap");
        var geoc = new BMap.Geocoder();

        var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
        var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
        var top_right_navigation = new BMap.NavigationControl({
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            type: BMAP_NAVIGATION_CONTROL_SMALL
        }); //右上角，仅包含平移和缩放按钮
        /*缩放控件type有四种类型:
         BMAP_NAVIGATION_CONTROL_SMALL：仅包含平移和缩放按钮；BMAP_NAVIGATION_CONTROL_PAN:仅包含平移按钮；BMAP_NAVIGATION_CONTROL_ZOOM：仅包含缩放按钮*/
        map.addControl(top_left_control);
        map.addControl(top_left_navigation);
        map.addControl(top_right_navigation);

        //map.centerAndZoom('贵州', 12);

        function addMarker (lng, lat, zoom) {
            if (lng == 0 || lat == 0) {//未设置，不处理
                return;
            }
            map.clearOverlays();
            var point = new BMap.Point(lng, lat);
            var marker = new BMap.Marker(point);
            map.addOverlay(marker);
            map.centerAndZoom(point, zoom);
        }

        /**
         * 点击地图 增加站点
         * @param e 事件
         */
        function addSite (e) {
            var pt = e.point;
            addMarker(pt.lng, pt.lat);
            geoc.getLocation(pt, function (rs) {
                var addComp = rs.addressComponents;
                console.dir(rs);
                //alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
                var name = '';
                if (rs.surroundingPois && rs.surroundingPois.length > 0) {
                    var poi = rs.surroundingPois[0];
                    if (poi.title) {
                        name = poi.title;
                    } else {
                        name = poi;
                    }
                } else {
                    name = rs.address;
                }
                $scope.routeSite.name = name;
                $scope.routeSite.latitude = rs.point.lat;
                $scope.routeSite.longitude = rs.point.lng;

                $scope.$apply();
            });
        }

        //有bug，不显示地点的名字 屏蔽点击改变站点
        //map.addEventListener("click", addSite);

        // 百度地图API功能
        function G (id) {
            return document.getElementById(id);
        }

        var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
            {
                "input": "suggestId",
                "location": map
            });

        ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
            var str = "";
            var _value = e.fromitem.value;
            var value = "";
            if (e.fromitem.index > -1) {
                value = _value.province + _value.city + _value.district + _value.street + _value.business;
            }
            str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

            value = "";
            if (e.toitem.index > -1) {
                _value = e.toitem.value;
                value = _value.province + _value.city + _value.district + _value.street + _value.business;
            }
            str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
            G("searchResultPanel").innerHTML = str;
        });

        var myValue;
        ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
            var _value = e.item.value;
            myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
            G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

            setPlace();
        });

        function setPlace () {
            function myFun () {
                console.dir(local.getResults().getPoi(0));
                var poi = local.getResults().getPoi(0);
                var pp = poi.point;    //获取第一个智能搜索的结果

                $scope.routeSite.name = $("#suggestId").val();
                $scope.routeSite.latitude = pp.lat;
                $scope.routeSite.longitude = pp.lng;
                $scope.$apply();

                addMarker(pp.lng, pp.lat, 18);
            }

            var local = new BMap.LocalSearch(map, { //智能搜索
                onSearchComplete: myFun
            });
            local.search(myValue);
        }

    }

    controller.$inject = deps;
    app.lazy.controller("RouteSiteEditController", controller);
});
